import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/common/global.dart';
import 'package:flutter_smart_heating/config/config.dart';
import 'package:flutter_smart_heating/config/lang.dart';
import 'package:flutter_smart_heating/routes/routes.dart';
import 'package:flutter_smart_heating/service/auth_service.dart';
import 'package:flutter_smart_heating/service/main_service.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:get_storage/get_storage.dart';

Future<void> main() async {
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
  SystemChrome.setPreferredOrientations([
    // 强制竖屏
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown
  ]);
  // 消除安卓状态栏蒙版
  if (GetPlatform.isAndroid) {
    SystemUiOverlayStyle systemUiOverlayStyle =
        const SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }

  await initServices();
  runApp(const MyApp());
}

Future<void> initServices() async {
  FlutterNativeSplash.remove();
  await GetStorage.init();
  await GlobalData.init();
  await Get.putAsync(() => AuthService().init());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      showPerformanceOverlay: false,
      title: Config.appName,
      themeMode: UiTheme.mode,
      darkTheme: ThemeData(
        scaffoldBackgroundColor: UiTheme.background,
        brightness: Brightness.dark,
        splashFactory: NoSplash.splashFactory,
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
        hoverColor: Colors.transparent,
        dividerTheme: DividerThemeData(
          color: Colors.white.withOpacity(0.2),
          thickness: 0.2,
        ),
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            splashFactory: NoSplash.splashFactory,
          ),
        ),
        bottomSheetTheme: const BottomSheetThemeData(
          backgroundColor: UiTheme.background,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(
              top: Radius.circular(UiTheme.boxRadiusX),
            ),
          ),
        ),
        textButtonTheme: TextButtonThemeData(
          style: TextButton.styleFrom(
            splashFactory: NoSplash.splashFactory,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(UiTheme.boxRadiusX),
            ),
          ),
        ),
        outlinedButtonTheme: OutlinedButtonThemeData(
          style: OutlinedButton.styleFrom(
            splashFactory: NoSplash.splashFactory,
          ),
        ),
        bottomNavigationBarTheme: const BottomNavigationBarThemeData(
          unselectedItemColor: Colors.white70,
          selectedItemColor: Color.fromARGB(255, 1, 131, 253),
          backgroundColor: Color.fromARGB(255, 8, 22, 68),
        ),
        appBarTheme: AppBarTheme(
          backgroundColor: UiTheme.background,
          elevation: 0,
          centerTitle: true,
          scrolledUnderElevation: 0,
          toolbarHeight: MediaQuery.of(context).size.width > 680
              ? 60
              : UiTheme.toolbarHeight,
          foregroundColor: Colors.white70,
          titleTextStyle: const TextStyle(
            fontSize: UiTheme.appBarTitleFontSize,
            color: Colors.white70,
            fontWeight: FontWeight.bold,
          ),
        ),
        textTheme: const TextTheme(
          bodyMedium: TextStyle(
            color: Colors.white70,
          ),
        ),
        iconTheme: const IconThemeData(
          color: Colors.white70,
        ),
        useMaterial3: true,
      ),
      theme: ThemeData(
        fontFamily: UiTheme.fontFamily,
        scaffoldBackgroundColor: const Color.fromARGB(255, 247, 248, 253),
        brightness: Brightness.light,
        splashFactory: NoSplash.splashFactory,
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
        hoverColor: Colors.transparent,
        dividerTheme: DividerThemeData(
          color: Colors.grey[300],
          thickness: 0.2,
        ),
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            splashFactory: NoSplash.splashFactory,
          ),
        ),
        bottomSheetTheme: const BottomSheetThemeData(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(
              top: Radius.circular(UiTheme.boxRadiusX),
            ),
          ),
        ),
        textButtonTheme: TextButtonThemeData(
          style: TextButton.styleFrom(
            splashFactory: NoSplash.splashFactory,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(UiTheme.boxRadiusX),
            ),
          ),
        ),
        outlinedButtonTheme: OutlinedButtonThemeData(
          style: OutlinedButton.styleFrom(
            splashFactory: NoSplash.splashFactory,
          ),
        ),
        bottomNavigationBarTheme: const BottomNavigationBarThemeData(
          backgroundColor: Colors.white,
          selectedItemColor: Color.fromARGB(255, 1, 131, 253),
        ),
        appBarTheme: AppBarTheme(
          backgroundColor: const Color.fromARGB(255, 247, 248, 253),
          elevation: 0,
          centerTitle: true,
          scrolledUnderElevation: 0,
          toolbarHeight: MediaQuery.of(context).size.width > 680
              ? 60
              : UiTheme.toolbarHeight,
          titleTextStyle: const TextStyle(
            fontSize: UiTheme.appBarTitleFontSize,
            color: Colors.black,
            fontWeight: FontWeight.bold,
          ),
        ),
        colorScheme: ColorScheme.fromSeed(seedColor: UiTheme.primary),
        textTheme: const TextTheme(
          bodyMedium: TextStyle(color: Colors.black),
        ),
        iconTheme: const IconThemeData(
          color: Colors.black,
        ),
        useMaterial3: true,
      ),
      translations: Lang(),
      locale: const Locale('zh', 'CN'),
      fallbackLocale: const Locale('en', 'US'),
      supportedLocales: const [
        Locale('zh', 'CN'),
        Locale('en', 'US'),
      ],
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate, //iOS
      ],
      initialRoute: '/splash',
      getPages: AppPages.pages,
      builder: (context, widget) {
        return MediaQuery(
          data: MediaQuery.of(context).copyWith(
            textScaler: TextScaler.noScaling,
          ),
          child: widget as Widget,
        );
      },
      routingCallback: (val) {
        if (val?.isBack == true) {
          GlobalData.history.removeLast();
        } else {
          GlobalData.history.add(val?.current);
        }
        if (val?.current != '/' &&
            val?.current != val?.previous &&
            val?.isBack == false) {
          App.report(val?.current.split('?').first);
        }
      },
      onInit: () {
        MainService.instance.init();
      },
    );
  }
}
